/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.pingan.mobilegw.core.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.pingan.mobilegw.adapterservice.ResultEnum;
import com.pingan.mobilegw.core.model.GatewayRequest;
import com.pingan.mobilegw.core.model.GatewayResponse;
import com.pingan.mobilegw.core.model.request.SingleRequestBody;
import com.pingan.mobilegw.core.service.business.Processor;
import com.pingan.mobilegw.core.service.util.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * 抽象处理器
 * <pre>
 *     主要处理mobilegw内部的业务逻辑，没有使用spi包的调用方式
 * </pre>
 * 
 * @author jiadao
 * @version $Id: AbstractBizProcessor.java, v 0.1 2013-4-4 下午9:13:41 jiadao Exp $
 */
public abstract class AbstractBizProcessor implements Processor {

    /** 默认logger */
    private static final Log logger = LogFactory.getLog(AbstractBizProcessor.class);


    @Override
    public GatewayResponse process(GatewayRequest gatewayRequest) {
        GatewayResponse gatewayResponse = null;
        SingleRequestBody requestBody = (SingleRequestBody) gatewayRequest.getRequestBody();
        try {
            gatewayResponse = execute(gatewayRequest, parseRequest(requestBody.getRequestData()));
        } catch (UndeclaredThrowableException e) {
            // 调用超时
            //TODOif (e.getUndeclaredThrowable() instanceof HSFTimeOutException) {
                //return ResponseUtil.buildErrorResponse(ResultEnum.RequestTimeOut);
            //}
            logger.error("远程调用异常", e);
            return ResponseUtil.buildErrorResponse(ResultEnum.RemoteAccessException);
        } catch (Throwable t) {
            logger.error("网关内业务业务执行异常", t);
            return ResponseUtil.buildErrorResponse(ResultEnum.UnknowError);
        }

        return gatewayResponse;

    }

    /**
     * 解析String为Object
     * <p>此类为默认实现
     * 序列化成请求对象,此处body可能是批处理或者正常流程过来的。
     * 批处理过来的对象为BchSingleRequestBody
     * 正常过来的为SingleRequestBody
     * 
     * @return
     */
    protected abstract Object parseRequest(String requestData);

    /**
     * 执行业务逻辑
    *
    * @param gatewayRequest 网关请求
    * @return 网关应答
    */
    protected abstract GatewayResponse execute(GatewayRequest gatewayRequest, Object req);

    /**
     * 将json装换为实体类
     * 
     * @param clazz 转换后的类
     * @return
     */
    protected Object initRequestFormJson(String requestData, Class<?> clazz) {
        return JSON.parseArray(requestData).getObject(0, clazz);
    }

}
